package com.hisense.proxy.busitrans.controller.iufo;

import com.alibaba.excel.EasyExcel;
import com.hisense.proxy.service.ncc.iufo.IufoSqlGenerateService;
import com.hisense.proxy.service.ncc.iufo.MeasureMngExcelData;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author tangxqa
 * @since 2022/10/12 09:01
 */
@RestController
@RequestMapping("/iufo")
@Api(tags = "企业报表sql生成工具")
public class IufoSqlGenerateController {

    @Resource
    private IufoSqlGenerateService generateService;

    // 获取类型列表
    @SneakyThrows
    @PostMapping(value = "/generate")
    @ApiOperation("生成SQL")
    public String generateSql(@RequestParam String reportPk, @RequestPart("excelFile") MultipartFile excelFile, @RequestPart("sqlTemplateFile") MultipartFile sqlTemplateFile) {

        byte[] bytes = excelFile.getBytes();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        List<MeasureMngExcelData> allData = EasyExcel.read(byteArrayInputStream)
                .head(MeasureMngExcelData.class)
                .headRowNumber(1)
                .sheet("all")
                .doReadSync();

        allData = allData.stream().filter(item -> Strings.isNotBlank(item.getCellLocation()))
                .collect(Collectors.toList());

        byteArrayInputStream = new ByteArrayInputStream(bytes);
        List<MeasureMngExcelData> specificData = EasyExcel.read(byteArrayInputStream)
                .head(MeasureMngExcelData.class)
                .headRowNumber(1)
                .sheet("specific")
                .doReadSync();
        specificData = specificData.stream().filter(item -> Strings.isNotBlank(item.getCellLocation()))
                .collect(Collectors.toList());

        String sqlTemplate = new String(sqlTemplateFile.getBytes(), StandardCharsets.UTF_8);

        String sql = generateService.getSql(reportPk, allData, specificData, sqlTemplate);

        return sql;
    }


}
